package net.dreamlu.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import net.dreamlu.api.oauth.OauthQQ;
import net.dreamlu.api.util.TokenUtil;
import net.dreamlu.common.WebUtils;
import net.dreamlu.common.base.BaseController;
import net.dreamlu.model.User;
import net.dreamlu.model.WbLogin;

import java.util.Date;

import static net.dreamlu.model.WbLogin.STATUS_N;

/**
 * qq登录api
 * @author L.cm
 * @date 2013-5-14 下午5:08:12
 */
public class QQLoginController extends BaseController {

    private static final String SESSION_STATE = "_SESSION_STATE_QQ_";

    public void index() {
        try {
            String state = TokenUtil.randomState();
            setSessionAttr(SESSION_STATE, state);
            redirect(OauthQQ.me().getAuthorizeUrl(state));
        } catch (Exception e) {
            logger.error(e.getMessage());
            redirect("/");
        }
    }

    /**
     * 腾讯回调
     * @Title: callback
     * @return void    返回类型
     * 返回json:<url>http://wiki.connect.qq.com/get_user_info</url>
     */
    public void callback() {
        String code = getPara("code");
        String state = getPara("state");
        String session_state = getSessionAttr(SESSION_STATE);
        // 取消了授权
        if (StrKit.isBlank(state) || StrKit.isBlank(session_state) || !state.equals(session_state) || StrKit.isBlank(code)) {
            redirect("/admin");
            return;
        }
        removeSessionAttr(SESSION_STATE);
        try{
            JSONObject userInfo = OauthQQ.me().getUserInfoByCode(code);
            logger.error(userInfo.toJSONString());
            String type = "qq";
            String openid = userInfo.getString("openid");
            String nickname = userInfo.getString("nickname");
            String photoUrl = userInfo.getString("figureurl_2");
            WbLogin login = WbLogin.dao.findByOpenID(openid, type);
            logger.error("login1:\t" + login);
            if(null == login) {
                login = new WbLogin();
                login.setOpenId(openid);
                login.setType(type);
                login.setHeadPhoto(photoUrl);
                login.setCreatetime(new Date());
                login.setStatus(WbLogin.STATUS_N);
                login.setNickname(nickname);
                login.save();
            }
            logger.error("login2:\t" + login);
            // 是否邮件校验通过
            int status = login.getStatus();
            if (null != login.getId() && STATUS_N == status) {
                if (null == login.getUserId()) {
                    setAttr("nouser", true);
                }
                // 跳转到绑定页
                setAttr("id", login.getId());
                setAttr("type", type);
                setAttr("nickname", nickname);
                setAttr("photourl", photoUrl);
                render("binding.jsp");
                return;
            }
            if (WbLogin.STATUS_Y == status) {
                User user = User.dao.findById(login.getUserId());
                WebUtils.loginUser(this, user, false);
            }
        }catch(Exception e){
            logger.error(e.getMessage());
        }
        redirect("/admin");
    }
}
